package com.jctrip.hotel.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;

/**
 * @Author henry
 * @Date 2023/7/1 16:34
 * @Description
 */
public class XMLUtil {
    public static <T> T convertXmlToObject(String xml, Class<T> beanType){
        if(null!=xml&&!"".equals(xml)){
            try {
                XmlMapper xmlMapper = new XmlMapper();
                //设置xml格式携带版本和编码信息<?xml version='1.0' encoding='UTF-8'?>
                xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);
                //字段值为null，自动忽略，不再序列化
                xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
                return xmlMapper.readValue(xml,beanType);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    public static String convertObjectToXml(Object object){
        if(object!=null){
            try {
                XmlMapper xmlMapper = new XmlMapper();
                //设置xml格式携带版本和编码信息<?xml version='1.0' encoding='UTF-8'?>
                xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);
                //字段值为null，自动忽略，不再序列化
                xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
                return xmlMapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

}
